package com.heatup.apt.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aliyun.openservices.ClientException;
import com.aliyun.openservices.ServiceException;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.OSSErrorCode;
import com.aliyun.openservices.oss.OSSException;
import com.aliyun.openservices.oss.model.CannedAccessControlList;
import com.aliyun.openservices.oss.model.OSSObject;
import com.aliyun.openservices.oss.model.OSSObjectSummary;
import com.aliyun.openservices.oss.model.ObjectListing;
import com.aliyun.openservices.oss.model.ObjectMetadata;


/**
 * oss文件上传工具类
 * <P>File name : OssFileUtil.java </P>
 * <P>Author : fangxiaowen </P> 
 * <P>Date : 2016年9月28日 </P>
 */
public class OssFileUtil {

	private static String BUCKET_NAME =String.valueOf(CommonPropertiesUtil.get("oss_bucket_name")).trim();// "youfang-image";
	private static final String accessKeyId =CommonPropertiesUtil.getString("oss_accessKeyId").trim(); //"LTAIq8EJDJWUTU7g";
	private static final String accessKeySecret =CommonPropertiesUtil.getString("oss_accessKeySecret").trim(); //"jrh4txyDGOn8lSYAETBfUB6Or8W0UQ";
	private static final String OSS_ENDPOINT =CommonPropertiesUtil.getString("oss_endpoint").trim();  //"http://oss-cn-shenzhen.aliyuncs.com/";
	public static final String PATH =CommonPropertiesUtil.getString("oss_path").trim();// "http://youfang-image.oss-cn-shenzhen.aliyuncs.com/";
	
	/**
	 * oss文件上传参数
	 * 
	 */
	public static Map<String, String> getOSSParam() {
		Map<String, String> param = new HashMap<String, String>();
		param.put("bucket", BUCKET_NAME);
		param.put("AccessKeyId", accessKeyId);
		param.put("AccessKeySecret", accessKeySecret);
		param.put("region", "oss-cn-shenzhen");
		param.put("oss_path", PATH);
		return param;
	}
	
	
	/**
	 * 文件上传
	 * OssFileUtil.uploadFile()<BR>
	 * <P>Author :  fangxiaowen </P>  
	 * <P>Date : 2016年9月28日 </P>
	 * @param uploadFilePath 路径
	 * @param Objectkey 文件名称
	 * @return 上传成功以后的地址
	 */
	public static String uploadFile(String uploadFilePath,String Objectkey){
		
		String randString = Math.random() + "";
		randString = randString.replace(".", "");
		String current_date = DateUtils.format(new Date(), DateUtils.datePatternAllSimple);
		Objectkey = current_date + "_" + randString +"_"+Objectkey;
		
		OSSClient client = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
		// ensureBucket(client, BUCKET_NAME);
        // setBucketPublicReadable(client, BUCKET_NAME);
        File file = new File(uploadFilePath);
		
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(file.length());
		//判断上传类型，多的可根据自己需求来判定
		if (uploadFilePath.endsWith("xml")) {
			objectMeta.setContentType("text/xml");
		}
		else if (uploadFilePath.endsWith("jpg") || uploadFilePath.endsWith("jpeg")) {
			objectMeta.setContentType("image/jpeg");
		}
		else if (uploadFilePath.endsWith("png")) {
			objectMeta.setContentType("image/png");
		}
		InputStream input;
		try {
			input = new FileInputStream(file);
			client.putObject(BUCKET_NAME, Objectkey, input, objectMeta);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return PATH + Objectkey;
	}
	
	/**
	 * 文件上传
	 * OssFileUtil.uploadFile()<BR>
	 * <P>Author :  lusa </P>  
	 * <P>Date : 2016年12月14日 </P>
	 * @param uploadFilePath 路径
	 * @param Objectkey 文件名称
	 * @return 上传成功以后的地址
	 */
	public static String uploadFileByIS(InputStream input,String contentType, Integer length, String Objectkey) {
		String randString = Math.random() + "";
		randString = randString.replace(".", "");
		String current_date = DateUtils.format(new Date(), DateUtils.datePatternAllSimple);
		Objectkey = current_date + "_" + randString +"_"+Objectkey;
		
		OSSClient client = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(length);
		//判断上传类型，多的可根据自己需求来判定
		if (contentType.endsWith("xml")) {
			objectMeta.setContentType("text/xml");
		}
		else if (contentType.endsWith("jpg") || contentType.endsWith("jpeg")) {
			objectMeta.setContentType("image/jpeg");
		}
		else if (contentType.endsWith("png")) {
			objectMeta.setContentType("image/png");
		}
		client.putObject(BUCKET_NAME, Objectkey, input, objectMeta);
		return PATH + Objectkey;
	}
	
	
	
	/**
	 * 删除一个Bucket中的图片
	 *
	 * @param fileName  存储的文件名
	 * @throws OSSException
	 * @throws ClientException
	 */
	public static void deleteFile(String fileName)throws OSSException, ClientException{
		try {
			int index = fileName.lastIndexOf("/");
			if(index > 0 && fileName.length() > 1){
				fileName = fileName.substring(index+1);
			}
			OSSClient client = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
			OSSObject obj = client.getObject(BUCKET_NAME, fileName);
			if(null != obj && !obj.getKey().equals("")){
				client.deleteObject(BUCKET_NAME, fileName);
			}
		}catch (Exception e){

		}
	}
	/**
	 * 删除一个Bucket和其中的Objects
	 * 
	 * @param client  OSSClient对象
	 * @param bucketName  Bucket名
	 * @throws OSSException
	 * @throws ClientException
	 */
	private static void deleteBucket(OSSClient client, String bucketName)throws OSSException, ClientException{
		ObjectListing ObjectListing = client.listObjects(bucketName);
		List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();
		for(int i = 0; i < listDeletes.size(); i++){
			String objectName = listDeletes.get(i).getKey();
			System.out.println("objectName = " + objectName);
			//如果不为空，先删除bucket下的文件
			client.deleteObject(bucketName, objectName);
		}
		client.deleteBucket(bucketName);
	}
	
	/**
	 * 创建Bucket
	 * 
	 * @param client  OSSClient对象
	 * @param bucketName  BUCKET名
	 * @throws OSSException
	 * @throws ClientException
	 */
	public static void ensureBucket(OSSClient client, String bucketName)throws OSSException, ClientException{
		try{
			client.createBucket(bucketName);
		}catch(ServiceException e){
			if(!OSSErrorCode.BUCKES_ALREADY_EXISTS.equals(e.getErrorCode())){
				throw e;
			}
		}
	}
	
	/**
	 * 把Bucket设置成所有人可读
	 * 
	 * @param client  OSSClient对象
	 * @param bucketName  Bucket名
	 * @throws OSSException
	 * @throws ClientException
	 */
	private static void setBucketPublicReadable(OSSClient client, String bucketName)throws OSSException, ClientException{
		//创建bucket
		client.createBucket(bucketName);
		
		//设置bucket的访问权限， public-read-write权限
		client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
	}
	
	
	
	public static void main(String[] args) throws Exception{
		String Objectkey = "1113a.png";
		String uploadFilePath = "E:\\images\\1.png";
	/*    OSSClient client = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
	*/	
		try {
			System.out.println(BUCKET_NAME);
			//System.out.println(uploadFile(uploadFilePath, Objectkey));
            //uploadFile(client, BUCKET_NAME, Objectkey, uploadFilePath);

        }catch(Exception e){
        	e.printStackTrace();
        }
	}
	
 
	
}
